/**
 * 初始化 WebSocket 的封装
 *
 *
 * @author wuchong
 */
(function () {

    var WebSocket = function (url, setMessageInnerHTML) {

        this.url = url;
        //获取 STOMP 子协议的客户端对象
        this.stompClient = null;
        this.setMessageInnerHTML = setMessageInnerHTML;
    };

    // 连接webSocket
    WebSocket.prototype = {
        connect: function () {
            // 建立连接对象（还未发起连接）
            var socket = new SockJS(this.url);
            this.stompClient = Stomp.over(socket);
            // 向服务器发起webSocket连接并发送CONNECT帧
            this.stompClient.connect(
                {},
                function connectCallback(frame) {
                    // 连接成功时（服务器响应 CONNECTED 帧）的回调方法
                    this.setMessageInnerHTML("连接成功");
                },
                function errorCallBack(error) {
                    // 连接失败时（服务器响应 ERROR 帧）的回调方法
                    this.setMessageInnerHTML("连接失败");
                });
        },
        //发送消息
        send: function (dest, messageJson) {
            this.stompClient.send(dest, {}, messageJson);
            this.setMessageInnerHTML("dest 你发送的消息:" + messageJson);
        },

        //订阅消息
        subscribe: function (url) {
            this.stompClient.subscribe(url, function (response) {
                this.setMessageInnerHTML("已成功订阅" + url);
                var result = JSON.parse(response.body);
                this.setMessageInnerHTML(url + "你接收到的消息为:" + result.date);
            });
        },

        //关闭连接
        disconnect: function () {
            if (this.stompClient !== null) {
                this.stompClient.disconnect();
            }
            this.setMessageInnerHTML("连接关闭")
        },
    }
});